// 系统信息
const sys = wx.getSystemInfoSync()

// 画布上下文
let preCtx = null
// 图片原始路径和大小
let originPath = ''
// 当前展示的图片实际大小
// 裁剪后还可以继续裁剪
let imageWidth = 0
let imageHeight = 0

// 以下为裁剪框缩放时临时变量
// 当前操作的缩放角
let activeCorner = ''
// 裁剪框缩放前的位置信息
let clipBoxBeforeScaleClipX = 0
let clipBoxBeforeScaleClipY = 0
// 裁剪框缩放前的宽高
let clipBoxBeforeScaleWidth = 0
let clipBoxBeforeScaleHeight = 0
// 裁剪框缩放前点击鼠标的Page(X|Y)位置信息
let clipBoxBeforeScalePageX = 0
let clipBoxBeforeScalePageY = 0

// 以下为裁剪框移动时临时变量
// 裁剪框移动鼠标内部位置信息
let clipBoxMoveInnerX = 0
let clipBoxMoveInnerY = 0

// 图片在窗口面板尺寸小的缩放比
let xScale = 1
let yScale = 1

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showClipImg:false,//显示是否截图按钮
    //showBtn:false,
    showBtn:true,
    showModal: false, // 显示modal弹窗
    show_filename:false,  //显示新建文件名或者选择文件框
    single: false,// false 只显示一个按钮，如果想显示两个改为true即可
    filename:"",
    selectbtn_show:true,   //箭头切换
    isExsitFile:false,
    selectcontent:[],
    value:undefined,   //选中的值
    valueid:undefined,  //选中的id
    takePhotoText:"拍照",

    imagePath:"",
    originWidth: 0,
    originHeight: 0,

    // 图片显示面板宽高
    panelWidth: 0,
    panelHeight: 0,

    // 裁剪区域宽高
    clipWidth: 0,
    clipHeight: 0,
    // 裁剪区域位置信息
    clipX: 0,
    clipY: 0,
    // 裁剪区域底图位置信息
    clipImgX: 0,
    clipImgY: 0,

    // 正要裁剪的宽高
    croppingImageWidth: 0,
    croppingImageHeight: 0,

    type:"new",  //判断是哪种操作 新建文件 还是添加到已有文件 默认是新建文件
    filename:"",
    show_append_text:false //添加文字modal框
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.ctx = wx.createCameraContext()
    let type = options.type

    if(type!=undefined){
      that.setData({
        type:type
      })
    }
    let filename = options.filename
    if(filename != undefined){
      that.setData({
        filename:filename
      })
    }    
  },

  init () {
    preCtx = wx.createCanvasContext('main')
  },

  takePhoto() {
    let that = this

    if(that.data.takePhotoText=="重新拍照"){
      that.setData({
        // showBtn:false,
        showBtn:true,
        src: "",
        imagePath:"",
        takePhotoText:"拍照",
        showClipImg:false
      })  
    }else{
      that.ctx.takePhoto({
        quality: 'high',
        success: (res) => {         
          let data = res.tempImagePath
          that.setData({
            showBtn:true,
            src: data,
            imagePath:data,
            takePhotoText:"重新拍照",
            showClipImg:false
          })              
          originPath = data
          wx.getImageInfo({
            src: data,         
            success:(imgInfo)=>{        
              that.setData({
                originWidth: imgInfo.width,
                originHeight: imgInfo.height
              })
              that.initImage(imgInfo.width, imgInfo.height, originPath)     
            }
          })       
        }
      })
    }
  },

  initImage (imgWidth, imgHeight, imagePath) {
    let that = this
    this.setData({
      clipX: 0,
      clipY: 0,
      clipImgX: 0,
      clipImgY: 0
    })

    // 初始化图片，根据窗口大小，设置图片面板尺寸
    let panelW = sys.windowWidth - 20
    let panelH = sys.windowHeight - 60
    if (panelH / panelW >= imgHeight / imgWidth) {
      panelH = parseInt(panelW * imgHeight / imgWidth)
    } else {
      panelW = parseInt(panelH * imgWidth / imgHeight)
    }
    imageWidth = imgWidth
    imageHeight = imgHeight

    xScale = panelW / imageWidth
    yScale = panelH / imageHeight

    that.setData({
      imagePath,
      panelWidth: panelW,
      panelHeight: panelH,
      clipWidth: panelW,
      clipHeight: panelH,
      croppingImageWidth: imgWidth,
      croppingImageHeight: imgHeight
    })
  },

  textOCR(){
    let that = this
    wx.showLoading({
      title: '正在努力识别中',
    })

    that.setData({
      showClipImg:false
    })
    wx.uploadFile({
      //url: 'http://121.37.180.71:8002/myocr', 
      url:'https://admin.yzqysoft.com:8002/myocr',
      filePath: that.data.imagePath,
      name: 'file',
      success: function(res){
        var data = res.data
        data = data.slice(1,data.length-1)
        that.setData({
          ocr_content:data,
          showModal:true
        })
        wx.hideLoading()
       
      }
    })
  },

    /**
   * 新的识别文字逻辑 原来逻辑不变 调用textOCR就可以 ，新的逻辑是不使用截图按钮，截图不会单独放在页面上，识别文字前把截图的事情先做完
   */
  newOCR(){
    const { imagePath, croppingImageWidth, croppingImageHeight, panelHeight, panelWidth, clipImgX, clipImgY } = this.data
    if (!imagePath) {
      return
    }
    wx.showLoading({ title: '正在裁剪...' })
    preCtx.clearRect(0, 0, imageWidth, imageHeight)    

    const width = croppingImageWidth
    const height = croppingImageHeight
    const xPos = Math.abs(clipImgX / xScale)
    const yPos = Math.abs(clipImgY / yScale)

    preCtx.drawImage(imagePath, xPos, yPos, width, height, 0, 0, width, height)
    preCtx.save()
    preCtx.restore()

    const that = this
    preCtx.draw(false, function () {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width,
          height,
          destWidth: width,
          destHeight: height,
          canvasId: 'main',
          success: (canRes) => {
            wx.hideLoading()
         
            that.newTextOCR(canRes.tempFilePath)
            // if(that.data.showClipImg){
            //   that.initImage(width, height, canRes.tempFilePath)        //显示截图按钮，需要画截图图片的时候才initImage
            // }       
          },
          fail (err) {
            wx.hideLoading()
            console.log(err)
          }
        })
      }, 200)
    })
  },

  myCopyText(e){
    let that = this
    let data = that.data.ocr_content
    wx.setClipboardData({
      data: that.data.ocr_content,
      success (res) {      
        // that.setData({
        //   showModal:false
        // })
      },
      fail(err){
        console.log(err)
      }
    })
  },

  /**
   * 追加文字回调   * 
   */
  myAppendTxt(){
    let that = this
    let filename_suffix = that.data.filename
    let filename = filename_suffix.slice(0,filename_suffix.length - 5) //此处的文件名默认有.docx后缀，要不这个后缀去掉    

    let ocr_content = that.data.ocr_content
    let openid = wx.getStorageSync('openid')

    wx.request({
      method:"post",
      header: {
        'content-type': 'application/json' 
      },
      url:'https://admin.yzqysoft.com:8002/sendAppendContent',
      data: {
        fileName:filename,
        content:ocr_content,
        openid:openid
      },    
      success (res) {
        // 预览网络文档
        wx.downloadFile({
          //url: "http://121.37.180.71:8002/static/tmp_docx/"+openid+"/"+filename+".docx", // 文件的本身url
          url: "https://admin.yzqysoft.com:8002/static/tmp_docx/"+openid+"/"+filename+".docx", // 文件的本身url
          filePath: wx.env.USER_DATA_PATH + '/'+filename+".docx", // 本地自定义的文件名
          success: function (res) {
            let filePath = res.filePath; // 微信临时文件路径(这里要使用自定义的名字文件名,否则打开的文件名是乱码)
            wx.openDocument({
              filePath: filePath,
              showMenu: true,  // 是否显示右上角菜单按钮 默认为false(看自身需求，可要可不要。后期涉及到右上角分享功能)
              success: function () {
               wx.showToast({
                 title: '打开文件成功',
               })
              },
              fail: function() {
                wx.showToast({ title: '打开文件失败，请稍后重试' });
              }
            });           
          },
          fail: function() {
            wx.showToast({ title: '打开文件失败，请稍后重试' });           
          }
        });
      }
    })



  },

  myExportTxt(e){
    let that = this   
    let content = that.data.ocr_content

    that.setData({
      show_filename:true
    })   
    
  },

  /*
  **input_blur 面对有些手机没有完成按钮 使用这个方法获取文件名
  */
  bind_input(e){
    let that = this  

    that.setData({
      filename:e.detail.value,
      isExsitFile:false
    })   
  },
  

  /*新建文件或者选择文件*/
  filename_cancel(){
    let that = this
    that.setData({
      show_filename:false
    })
  },

  /**创建新文件*/
  createNewWord(s){
    let that = this
    let openid = wx.getStorageSync('openid')
    let filename = that.data.filename
    let ocr_content = that.data.ocr_content
    let url = s
    if(filename == "" || filename == undefined){
      wx.showToast({
        title: '请重新输入文件名',
      })      
      return
    }

    wx.request({
      method:"post",
      header: {
        'content-type': 'application/json' 
      },     
      url:url,
      data: {
        fileName:filename,
        content:ocr_content,
        openid:wx.getStorageSync('openid')
      },    
      success (res) {
        // 预览网络文档
        wx.downloadFile({    
          url:"https://admin.yzqysoft.com:8002/static/tmp_docx/"+openid+"/"+filename+".docx", // 文件的本身url
          filePath: wx.env.USER_DATA_PATH + '/'+filename+".docx", // 本地自定义的文件名
          success: function (res) {
            let filePath = res.filePath; // 微信临时文件路径(这里要使用自定义的名字文件名,否则打开的文件名是乱码)
            wx.openDocument({
              filePath: filePath,
              showMenu: true,  // 是否显示右上角菜单按钮 默认为false(看自身需求，可要可不要。后期涉及到右上角分享功能)
              success: function () {
                wx.showToast({
                  title: '打开文件成功',
                })            
                that.setData({
                  show_filename:false,
                  filename:""
                })
              },
              fail: function() {
                wx.showToast({ title: '打开文件失败，请稍后重试' });
              }
            });           
          },
          fail: function() {
            wx.showToast({ title: '打开文件失败，请稍后重试' });           
          }
        });
      }
    })
  },

  /**确定选择哪个文件 */
  filename_confirm(){
    let  that = this 
    let filename = that.data.filename
    let ocr_content = that.data.ocr_content
    let isExsitFile = that.data.isExsitFile

    let url = ""
    let openid = wx.getStorageSync('openid')

    wx.request({
      method:"POST",
      header: {
        'content-type': 'application/json' 
      },  
      url:'https://admin.yzqysoft.com:8002/getExsitFiles',
      data:{
        openid:wx.getStorageSync('openid')
      },
      success:function(res){
         //["doc1", "doc1.docx"]
        let data_arr = res.data      
      
        if(data_arr.length != 0){          
          let exist = false         
       
          /**此处设置一个exsit中是因为 forEach 怎么都不呢能break中断 目前只能这样标记 当前文件名存不存在 */
          data_arr.forEach(function(value,index){
              //var value = data_arr[index]
              let suffix_index = value.indexOf(".docx")
              let data = ""
              if(suffix_index != -1){
                data = value.slice(0, suffix_index)
              }
           
              //||filename.indexOf("已存在,请点击首页追加内容按钮")!=0
              if(data == filename){
                exist = true                           
              }    
          }) 
         
          if(exist){
            that.setData({
              isExsitFile:true, /*选择了已存在的文件*/      
              //filename:filename+"已存在,请点击首页追加内容按钮"
            })
          }else{
            that.setData({
              filename:filename,
              isExsitFile:false, /**表示是新建的文件*/
            })

            url = 'https://admin.yzqysoft.com:8002/sendNewContent'
            that.createNewWord(url)
          }       
        }else if(data_arr.length == 0){
          that.setData({
            filename:filename,
            isExsitFile:false, /**表示是新建的文件*/
          })

          url = 'https://admin.yzqysoft.com:8002/sendNewContent'
          that.createNewWord(url)
        }  
      },
      fail:function(err){
        console.log(err)
      }
    })  
  },

  close_modal(){
    let that = this
    that.setData({
      show_filename:false
    })
  },

  /**
   * 关闭追加文字对话框
   */
  close_appendText_btn(){
    let that = this
    that.setData({
      show_append_text:false
    })
  },

  // 下拉框收起和下拉
  changeSelect(){
    let that = this

    //如果这个时候 选文件的对话框没有弹出来，那么说明我们要请求一次文件类表，为文件选择框做准备    
    if(this.data.selectbtn_show){
      wx.request({
        method:"POST",
        //url: 'http://121.37.180.71:8002/getExsitFiles',
        url: 'https://admin.yzqysoft.com:8002/getExsitFiles',
        header: {
          'content-type': 'application/json' 
        },
        data:{
          openid:wx.getStorageSync('openid')
        },
        success:function(res){
           //["doc1", "doc1.docx"]
          let data_arr = res.data
          let tmp_content = []
          data_arr.forEach(function(value,index){
            let suffix_index = value.indexOf(".docx")
            let data = ""
            if(suffix_index != -1){
              data = value.slice(0, suffix_index)
            }

            let tmp_item = {id:index+1, name:data}
            tmp_content.push(tmp_item)
          })
          that.setData({
            selectcontent:tmp_content
          })
        },
        fail:function(err){
          console.log(err)
        }
      })
    }
    this.setData({
      selectbtn_show:!this.data.selectbtn_show
    })
  },
  // 选择数据后回显
  changecontent(e){
    this.setData({
      filename:e.currentTarget.dataset.datavalue.name,
      isExsitFile:true, /**表示选择的是已经存在的文件 */
      /**value:e.currentTarget.dataset.datavalue.name,*/
      valueid:e.currentTarget.dataset.datavalue.id,
      selectbtn_show:true
    })
  },

  touchstartM (event) {
    let that = this
    const { clipX, clipY } = that.data
    const { pageX, pageY } = event.touches[0]
    // 获取鼠标点在裁剪框的内部位置信息
    clipBoxMoveInnerX = pageX - clipX
    clipBoxMoveInnerY = pageY - clipY

    that.setData({
      showClipImg:true, //确认截图按钮显示
      //showBtn:false     //识别文字按钮需要隐藏
      showBtn:true
    })
  },

  touchmoveM (event) {
    const { pageX, pageY } = event.touches[0]
    const { panelWidth, panelHeight, clipHeight, clipWidth } = this.data

    // 裁剪框不能脱离面板
    // X位置范围为 0 到 (面板宽度-裁剪框宽度)
    let clipX = pageX - clipBoxMoveInnerX
    clipX = Math.max(clipX, 0)
    const panelX = panelWidth - clipWidth
    clipX = Math.min(clipX, panelX)
    // Y位置范围为 0 到 (面板高度-裁剪框高度)
    let clipY = pageY - clipBoxMoveInnerY
    clipY = Math.max(clipY, 0)
    const panleY = panelHeight - clipHeight
    clipY = Math.min(clipY, panleY)

    // 裁剪框底图位置信息
    const clipImgX = 0 - clipX
    const clipImgY = 0 - clipY

    this.setData({
      clipX,
      clipY,
      clipImgX,
      clipImgY,
      showClipImg:true, //确认截图按钮显示
      //showBtn:false     //识别文字按钮需要隐藏
      showBtn:true
    
    })
  },

   // 处理缩放动作中不同corner时的尺寸位置信息
   getClipX (clipWidth) {   
    switch (activeCorner) {
      case 'leftTop': 
      case 'leftBottom':       
        return clipBoxBeforeScaleClipX + (clipBoxBeforeScaleWidth - clipWidth)
      case 'rightTop':
      case 'rightBottom':       
        return clipBoxBeforeScaleClipX;
      default:
        return 0
    }
  },
  getClipY (clipHeight) {  
    switch (activeCorner) {
      case 'leftTop':
      case 'rightTop':
        return clipBoxBeforeScaleClipY + (clipBoxBeforeScaleHeight - clipHeight)
      case 'leftBottom':
      case 'rightBottom':
        return clipBoxBeforeScaleClipY
      default:
        return 0
    }
  },

  getScaleXWidthOffset (offsetW) {
    switch (activeCorner) {
      case 'leftTop':
      case 'leftBottom':
        return -offsetW
      case 'rightTop':
      case 'rightBottom':
        return offsetW
      default:
        return 0
    }
  },
  getScaleYHeightOffset (offsetH) {
    switch (activeCorner) {
      case 'rightBottom':
      case 'leftBottom':
        return offsetH
      case 'rightTop':
      case 'leftTop':
        return -offsetH
      default:
        return 0
    }
  },

  touchstart (event) {  
    let that = this
    const dragId = event.currentTarget.dataset.id
    //{clientX: 60.5,clientY: 14.75,force: 1,identifier: 0,pageX: 60.5,pageY: 14.75
    const { pageX, pageY } = event.touches[0]
    const { clipX, clipY, clipHeight, clipWidth } = this.data

    // 设置缩放时临时变量初始化值
    activeCorner = dragId
    clipBoxBeforeScalePageX = pageX
  
    clipBoxBeforeScalePageY = pageY
  
    clipBoxBeforeScaleClipX = clipX
   
    clipBoxBeforeScaleClipY = clipY
  
    clipBoxBeforeScaleWidth = clipWidth
  
    clipBoxBeforeScaleHeight = clipHeight

    that.setData({
      showClipImg:true, //确认截图按钮显示
      //showBtn:false     //识别文字按钮需要隐藏
      showBtn:true
    })
  },
  touchmove (event) {  
    const { pageX, pageY } = event.touches[0]
    const { panelWidth, panelHeight } = this.data

    // 缩放在X上的偏移
    const xWidthOffset = this.getScaleXWidthOffset(pageX - clipBoxBeforeScalePageX)  //topleft 0
   
    // 裁剪框最小宽度36
    let clipWidth = Math.max(clipBoxBeforeScaleWidth + xWidthOffset, 36)   
    // 设置缩放最大宽度，放大时不能超过面板、缩小时不能超过初始裁剪框
   
    let tempPanelWidth = pageX > clipBoxBeforeScalePageX ? panelWidth - clipBoxBeforeScaleClipX : clipBoxBeforeScaleWidth + clipBoxBeforeScaleClipX
   
    // 设置裁剪框宽度
    clipWidth = Math.min(clipWidth, tempPanelWidth)

    // 缩放在Y上的偏移
    const yHeightOffset = this.getScaleYHeightOffset(pageY - clipBoxBeforeScalePageY)
  
    // 裁剪框最小高度36
    let clipHeight = Math.max(clipBoxBeforeScaleHeight + yHeightOffset, 36)
  
    // 设置缩放最大高度，放大时不能超过面板、缩小时不能超过初始裁剪框
    
    let tempPanelHeight = pageY > clipBoxBeforeScalePageY ? panelHeight - clipBoxBeforeScaleClipY : clipBoxBeforeScaleHeight + clipBoxBeforeScaleClipY
    // 设置裁剪框高度
    clipHeight = Math.min(clipHeight, tempPanelHeight)

    // 裁剪框位置信息
    let clipX = this.getClipX(clipWidth)
    let clipY = this.getClipY(clipHeight)
    // 裁剪框底图位置信息
    let clipImgX = 0 - clipX
    let clipImgY = 0 - clipY

    this.setData({
      clipWidth,
      clipHeight,
      clipX,
      clipY,
      clipImgX,
      clipImgY,
      croppingImageWidth: parseInt(clipWidth / xScale),  //转换为真实图片的宽
      croppingImageHeight: parseInt(clipHeight / yScale),  //转换为真实图片的高
      showClipImg:true, //确认截图按钮显示
      //showBtn:false     //识别文字按钮需要隐藏
      showBtn:true
    })   
  },

  downloadCanvasImage () {
    const { imagePath } = this.data
    if (!imagePath) {
      return
    }
    wx.showLoading({ title: '保存中...' })
    savePhoto(imagePath)
  },

  getCropperImage () {
   
    const { imagePath, croppingImageWidth, croppingImageHeight, panelHeight, panelWidth, clipImgX, clipImgY } = this.data
    if (!imagePath) {
      return
    }
    wx.showLoading({ title: '正在裁剪...' })
    preCtx.clearRect(0, 0, imageWidth, imageHeight)    

    const width = croppingImageWidth
    const height = croppingImageHeight
    const xPos = Math.abs(clipImgX / xScale)
    const yPos = Math.abs(clipImgY / yScale)

    preCtx.drawImage(imagePath, xPos, yPos, width, height, 0, 0, width, height)
    preCtx.save()
    preCtx.restore()

    const that = this
    preCtx.draw(false, function () {
      setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width,
          height,
          destWidth: width,
          destHeight: height,
          canvasId: 'main',
          success: (canRes) => {
            wx.hideLoading()
            that.initImage(width, height, canRes.tempFilePath)
          },
          fail (err) {
            wx.hideLoading()
            console.log(err)
          }
        })
      }, 200)
    })

    that.setData({
      showClipImg:false, //确认截图后
      showBtn:true      //显示识别文字按钮
    })
  },

  /**
   * 不改变textOCR原来逻辑 原来的逻辑是点击 确认截屏按钮 执行getCropperImage 然后识别文字按钮显示 再点击发送被截的部分，来识别文字，
   * 先在将newOCR是把执行getCropperImage代码复制一份 在canva绘图成功后 执行先的newTextOCR 不改变getCropperImage和TextOCR,
   * newTextOCR和TextOCR唯一的区别就是 wx.uploadFile filepath的值不同 
   */
  newTextOCR(clipimgpath){
    let that = this
    wx.showLoading({
      title: '正在努力识别中',
    })
    that.setData({
      showClipImg:false
    })
    wx.uploadFile({
      //url: 'http://121.37.180.71:8002/myocr', 
      url:'https://admin.yzqysoft.com:8002/myocr',
      filePath:clipimgpath,
      name: 'file',
      success: function(res){
        var data = res.data
        data = data.slice(1,data.length-1)

        //新建识别任务
        if(that.data.type != "append"){
          that.setData({
            ocr_content:data,
            showModal:true
          })
        }else{ //追加文字
          that.setData({
            ocr_content:data,
            show_append_text:true
          })
        }
   
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let that = this
    that.init()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})